package com.heima;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolExecutorTest1 {

    public static void main(String[] args) throws Exception {
        /**
         * 创建线程池
         * 参数1表示定义的核心线程数量 5
         * 参数2表示池中允许的最大线程数量
         * 参数3表示线程存活时间
         * 参数4表示时间单位
         * 参数5表示用于在执行任务之前保存任务的队列
         */
        ThreadPoolExecutor thradPoll =new ThreadPoolExecutor(5,
                100,60,
                TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());

//        //执行任务 并返回结果
//        Future<String> future = thradPoll.submit(new myCallable("黑马程序员"));
//        String s = future.get();
//        System.out.println(s);

        //批量执行任务并返回任务的结果集合
        List<myCallable> taskList = new ArrayList<>(100);
        for(int i=0;i<100;i++){
            taskList.add(new myCallable("黑马程序猿"+i));
        }
        List<Future<String>> futureList = thradPoll.invokeAll(taskList);
        for (Future<String> future : futureList) {
            String s = future.get(5, TimeUnit.SECONDS);
            System.out.println(s);
        }

    }

    /**
     * 创建Callable接口实现
     */
    public static class myCallable implements Callable<String> {

        //定义名称
        private String name;

        public myCallable(String name){
            this.name=name;
        }

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public String call() throws Exception {
            System.out.println("execute my callable task"+Thread.currentThread().getName());

            return "hello "+name;
        }
    }
}
